package models;

import java.util.Date;
import java.util.List;

import siena.Column;
import siena.Generator;
import siena.Id;
import siena.Model;
import siena.Query;
import siena.Table;
import util.Utilities;

@Table("blog_entry")
public class BlogEntry extends Model {

	@Id(Generator.AUTO_INCREMENT)
	public Long id;
	
	@Column("title")
	public String title;
	
	@Column("content")
	public String content;
	
	@Column("create_time")
	public Date createTime;
	@Column("last_modify_time")
	public Date lastModifyTime;
	
	@Column("author_id")
	public Long authorId;
	
	public BlogEntry() {
		super();
	}
	
	public BlogEntry(String title, String content, Long authorId) {
		super();
		this.title = title;
		this.content = content;
		this.authorId = authorId;
	}

	public User author() {
		return Model.all(User.class).filter("id", authorId).get();
	}
	
	public String abstracts() {
		return Utilities.truncateNicely(content, 0, 400, "...");
	}
	
	public List<Tag> tags() {
		return TagReference.getTags(id);
	}
	
	public String tagsStr() {
		List<Tag> tags = TagReference.getTags(id);
		String str = "";
		if(tags != null && !tags.isEmpty()) {
			for(Tag t : tags) {
				str += t.name + ",";
			}
			str = str.substring(0, str.lastIndexOf(","));
		}		
		return str;
	}
	
	public void saveTags(String tagsStr) {
		if(tagsStr == null || "".equals(tagsStr)) {
			return;
		}
		String[] tags = tagsStr.split(",");
		if(tags != null && tags.length > 0) {
			for(int i = 0; i < tags.length; i++) {
				String name = tags[i];
				
				Tag t = Tag.get(name);
				if(t == null) {
					t = new Tag(name);
					t.insert();
				}
				
				TagReference ref = new TagReference(id, t.id);
				ref.insert();
			}
		}
	}
	
	public static BlogEntry get(Long id) {
		return all().filter("id", id).get();
	}
	
	public static Query<BlogEntry> all() {
		return Model.all(BlogEntry.class);
	}
	
}
